package com.yanq.liancar.wxapi;
/*
 *  @创建者     liyan
 *  @创建时间   2018/9/9  11:49
 *  @描述       ${TODO}
 */


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.RxSPTool;
import com.vondear.rxtool.view.RxToast;
import com.yanq.liancar.activity.LoginActivity;
import com.yanq.liancar.activity.MinUserMainActivity;
import com.yanq.liancar.bean.BaseBean;
import com.yanq.liancar.bean.UserBean;
import com.yanq.liancar.bean.WeChatLoginBean;
import com.yanq.liancar.bean.WeChatUserInfoBean;
import com.yanq.liancar.bean.loginUserBean;
import com.yanq.liancar.url.Config;
import com.yanq.liancar.util.LogUtils;

import java.net.URLEncoder;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

    private IWXAPI api;
    private BaseResp resp = null;
    private String WX_APP_ID = "wxd2e19fc6b6f17ec0";
    // 获取第一步的code后，请求以下链接获取access_token
    private String GetCodeRequest = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
    // 获取用户个人信息
    private String GetUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";

    //private String WX_APP_SECRET = "633c5c36b6849da6592974ad2836db82";
    private String WX_APP_SECRET = "2e69c6a579d12388d376606be9ef0774";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        api = WXAPIFactory.createWXAPI(this, WX_APP_ID, false);
        api.handleIntent(getIntent(), this);

    }

    // 微信发送请求到第三方应用时，会回调到该方法
    @Override
    public void onReq(BaseReq req) {
        LogUtils.e("1111111",req.toString()+"");

        //finish();
    }

    // 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
    @Override
    public void onResp(BaseResp resp) {
        String result = "";
        if (resp != null) {
            resp = resp;
        }
        LogUtils.e("22222222222",resp.errCode+"");


        if (resp.getType()== ConstantsAPI.COMMAND_PAY_BY_WX){
            if (resp.errCode==0){
                RxToast.success("支付成功");
            }else if (resp.errCode==-2){
                RxToast.error("支付取消");
            }else {
                RxToast.error("支付失败");
            }
        }

        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                if (resp.getType()==2){
                    //微信分享返回
                    finish();
                }else {
                    result = "发送成功";
                    Toast.makeText(this, result, Toast.LENGTH_LONG).show();
                    String code = ((SendAuth.Resp) resp).code;
                    LogUtils.e("code====",code);
                    /*
                     * 将你前面得到的AppID、AppSecret、code，拼接成URL 获取access_token等等的信息(微信)
                     */

                    String get_access_token = getCodeRequest(code);
                    getAccess_token(get_access_token);
                }
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                result = "发送取消";
                Toast.makeText(this, result, Toast.LENGTH_LONG).show();
                finish();
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                result = "发送被拒绝";
                Toast.makeText(this, result, Toast.LENGTH_LONG).show();
                finish();
                break;
            default:
                result = "发送返回";
                Toast.makeText(this, result, Toast.LENGTH_LONG).show();
                finish();
                break;
        }
    }

    /**
     * 通过拼接的用户信息url获取用户信息
     *
     * @param user_info_url
     */
    private void getUserInfo(String user_info_url) {
        OkGo.<String>post(user_info_url)
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        LogUtils.e("11111111111",response.body().toString());
                        if (!response.equals("")) {
                            Gson gson=new Gson();
                            WeChatUserInfoBean bean=gson.fromJson(response.body(),WeChatUserInfoBean.class);
                            String openid =bean.getOpenid();
                            String nickname =bean.getNickname();
                            String headimgurl =bean.getHeadimgurl();

                            if ("login".equals(RxSPTool.getString(WXEntryActivity.this, "WeChatType"))){
                                OkGo.<String>post(Config.s+"llc/weChatLogin")
                                        .tag(this)
                                        .params("chatJson",response.body())
                                        .execute(new StringCallback() {
                                            @Override
                                            public void onSuccess(Response<String> response) {
                                                LogUtils.e("11111111111",response.body().toString());
                                                if (!response.equals("")) {
                                                    Gson gson=new Gson();
                                                    loginUserBean bean = gson.fromJson(response.body(), loginUserBean.class);
                                                    if (bean.isIsSuccess()) {
                                                        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                                                        // 隐藏软键盘
                                                        imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
                                                        LogUtils.e("1111111",bean.getData().getToken());
                                                        UserBean.setID(WXEntryActivity.this, bean.getData().getUser().getUid());
                                                        RxSPTool.putString(WXEntryActivity.this, "UserPhone", bean.getData().getUser().getTel());
                                                        UserBean.setcToken(WXEntryActivity.this, bean.getData().getToken());
                                                        UserBean.setName(WXEntryActivity.this, bean.getData().getUser().getUsername());
                                                        UserBean.setSign(WXEntryActivity.this, bean.getData().getUser().getSign());

                                                        Bundle bundle = new Bundle();
                                                        bundle.putInt("type", 4);
                                                        RxActivityTool.skipActivityAndFinish(WXEntryActivity.this, MinUserMainActivity.class, bundle);
                                                        RxToast.success(bean.getOutputMessage());
                                                    } else {
                                                        RxToast.error(bean.getOutputMessage());
                                                    }

                                                }
                                            }
                                            @Override
                                            public void onError(Response<String> response) {
                                                RxToast.error("服务器连接失败");
                                                LogUtils.e("asdasdad",response.code()+"");
                                                LogUtils.e("asdasdad",response.message()+"");
                                                super.onError(response);
                                            }
                                        });
                            }else {
                                OkGo.<String>post(Config.s+"llc/bindWeChat")
                                        .tag(this)
                                        .params("token",UserBean.getcToken(WXEntryActivity.this))
                                        .params("openid",openid)
                                        .execute(new StringCallback() {
                                            @Override
                                            public void onSuccess(Response<String> response) {
                                                LogUtils.e("11111111111",response.body().toString());
                                                if (!response.equals("")) {
                                                    Gson gson=new Gson();
                                                    BaseBean bean = gson.fromJson(response.body(), BaseBean.class);
                                                    if (bean.isIsSuccess()) {
                                                        RxToast.success(bean.getOutputMessage());
                                                        finish();
                                                    } else {
                                                        RxToast.error(bean.getOutputMessage());
                                                    }

                                                }
                                            }
                                            @Override
                                            public void onError(Response<String> response) {
                                                RxToast.error("服务器连接失败");
                                                LogUtils.e("asdasdad",response.code()+"");
                                                LogUtils.e("asdasdad",response.message()+"");
                                                super.onError(response);
                                            }
                                        });
                            }

                        }
                    }
                    @Override
                    public void onError(Response<String> response) {
                        RxToast.error("服务器连接失败");
                        LogUtils.e("asdasdad",response.code()+"");
                        LogUtils.e("asdasdad",response.message()+"");
                        super.onError(response);
                    }
                });

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
        finish();
    }

    /**
     * 获取access_token的URL（微信）
     *
     * @param code 授权时，微信回调给的
     * @return URL
     */
    private String getCodeRequest(String code) {
        String result = null;
        GetCodeRequest = GetCodeRequest.replace("APPID", urlEnodeUTF8(Config.WX_APP_ID));
        GetCodeRequest = GetCodeRequest.replace("SECRET", urlEnodeUTF8(WX_APP_SECRET));
        GetCodeRequest = GetCodeRequest.replace("CODE", urlEnodeUTF8(code));
        result = GetCodeRequest;
        return result;
    }

    /**
     * 获取用户个人信息的URL（微信）
     *
     * @param access_token 获取access_token时给的
     * @param openid       获取access_token时给的
     * @return URL
     */
    private String getUserInfo1(String access_token, String openid) {
        String result = null;
        GetUserInfo = GetUserInfo.replace("ACCESS_TOKEN", urlEnodeUTF8(access_token));
        GetUserInfo = GetUserInfo.replace("OPENID", urlEnodeUTF8(openid));
        result = GetUserInfo;
        return result;
    }

    private String urlEnodeUTF8(String str) {
        String result = str;
        try {
            result = URLEncoder.encode(str, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private void getAccess_token(String url){
        OkGo.<String>post(url)
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        LogUtils.e("11111111111",response.body().toString());
                        if (!response.equals("")) {
                            Gson gson=new Gson();
                            WeChatLoginBean bean=gson.fromJson(response.body(),WeChatLoginBean.class);
                            String access_token = bean.getAccess_token();
                            String openid =bean.getOpenid();
                            String get_user_info_url = getUserInfo1(
                                    access_token, openid);

                                getUserInfo(get_user_info_url);

                        }
                    }
                    @Override
                    public void onError(Response<String> response) {
                        RxToast.error("服务器连接失败");
                        LogUtils.e("asdasdad",response.code()+"");
                        LogUtils.e("asdasdad",response.message()+"");
                        super.onError(response);
                    }
                });
    }
}
